package DML;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import DuiXiang.TableModel;

public class DeleteData {

	@SuppressWarnings("finally")
	public static int deleteDataFromTable(String dataBaseName,
			String tableName, List<String> name, List<String> values,boolean all) {
		
		int i, number;
		int[] temp = new int[20];
		String dbfPath = "D:\\database\\" + dataBaseName + "\\" + tableName
				+ ".dbf";
		String datPath = "D:\\database\\" + dataBaseName + "\\" + tableName
				+ ".dat";
		List<TableModel> tableModelList = util.ReadTableModelList(dbfPath);
		List<List<String>> tableContent = util.readTable(datPath);
		if (tableContent == null)
			return -1; // 无此表或数据库
		if(!all){
		number = 0;
		for (String nn : name) {
			i = 0;
			for (TableModel aa : tableModelList) {
				if (aa.getsFieldName().equals(nn))
					break;
				i++;
			}
			temp[number++] = i;
		}
		for (int k = 0; k < tableContent.size(); k++) {
			for (i = 0; i < number; i++) {
				String a = tableContent.get(k).get(temp[i]);
				String b = values.get(i);
				if (!a.equals(b))
					break;
			}
			if (i == number)
				tableContent.remove(tableContent.get(k));
		}
		}
		else tableContent=null;
		File file = new File(datPath);
		if (file.delete())
			System.out.println("删除成功");
		else {
			System.out.println("删除失败");
			return 0; // 删除失败
		}
		
		
		FileWriter fileWriter = null;
		BufferedWriter bufferWriter = null;
		try {
			fileWriter = new FileWriter(datPath);
			bufferWriter = new BufferedWriter(fileWriter);
			for (List<String> aline1 : tableContent) {
				for (int k=0;k<aline1.size();k++) {
					bufferWriter.write(aline1.get(k));
					if(k<aline1.size()-1)
						bufferWriter.write(",");
					else
						bufferWriter.newLine();
					bufferWriter.flush();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		} finally {
			try {
				bufferWriter.close();
				fileWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return 1;
		}
		
	}
}
